import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'//导入登录组件
import Home from '../components/Home.vue'//导入Home组件
import Welcome from '../components/Welcome.vue'//导入Welcome组件
import Users from '../components/user/Users.vue'//导入User用户列表孙组件
import Rights from '../components/power/Rights.vue'//导入权限列表组件
import Roles from '../components/power/Roles.vue'//导入角色列表组件
import Cate from '../components/goods/Cate.vue'//导入商品分类组件
import Params from '../components/goods/Params.vue'//导入分类参数组件
import GoodsList from '../components/goods/List.vue'//导入商品列表组件
import Add from '../components/goods/Add.vue' //导入添加商品页面
import Order from '../components/order/Order.vue'//导入订单列表页面
import Report from '../components/report/Report.vue'//导入数据报表组件

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,//父组件--home
    redirect: '/welcome',
    children: [//子组件--welcome
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: Add },
      { path:'/orders',component:Order},
      { path:'/reports',component:Report}
    ]
  },

]

const router = new VueRouter({
  routes
})

//挂载全局路由导航守卫，控制访问权限，在跳转之前执行
//如果用户没有登录，但是直接通过URL访问特定页面，需要重新导航到登录页面。
//to:将要进入访问的路由规则/页面
//from:要离开的路由规则/页面
///next():直接跳转放行，   next('/login):强制跳转
router.beforeEach((to, from, next) => {
  //（1）访问的是登录页，直接放行
  if (to.path === '/login') {
    return next()
  }
  //（2）访问的不是登录页，先判断是否能获取到 toKen，根据是否有token决定能否跳转
  const tokenStr = window.sessionStorage.getItem("token")
  if (!tokenStr) {
    //false 没有token,没有登录过，无法直接跳转到home主页
    return next('/login')//强制跳转会登录页
  }
  //得到token，已登录过，可以跳转到home主页
  next()
})

export default router
